import urllib
import urllib.parse
import urllib.request
#import urllib2
import json
import time
import hmac, hashlib


def createTimeStamp(datestr, format="%Y-%m-%d %H:%M:%S"):
    return time.mktime(time.strptime(datestr, format))


class poloniex:
    def __init__(self, APIKey, Secret):
        self.APIKey = APIKey
        self.Secret = Secret

    def api_query(self, command, req={}):

        req['command'] = command
        req['nonce'] = int(time.time() * 1000)
        post_data = urllib.parse.urlencode(req).encode(encoding='utf-8')

        sign = hmac.new(self.Secret.encode(encoding='utf-8'), post_data, hashlib.sha512).hexdigest()
        headers = {
            'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36 LBBROWSER',
            'Sign': sign,
            'Key': self.APIKey
        }

        ret = urllib.request.urlopen(urllib.request.Request('https://poloniex.com/tradingApi', post_data, headers))
        jsonRet = json.loads(ret.read())
        return jsonRet


    # Returns all of your balances.
    # Outputs:
    # {"BTC":"0.59098578","LTC":"3.31117268", ... }
    def returnBalances(self):
        return self.api_query('returnCompleteBalances')

